<?php
/**
 * Контроллер писем
 * 
 * Управление письмами
 * @author Anton Zavidov
 * @package myLiveShop
 */

/**
 * Класс контроллера для управления письмами
 *
 */
class ControllerMail extends Element{
	/**
	 * Констуктор
	 *
	 * @param string $className имя контроллера
	 */
	public function __construct($className=null){
		$this->name='mail';
		parent::__construct($className?$className:__CLASS__);
	}
	/**
	 * Просмотр елемента
	 *
	 */
	public function show($page=false, $mode=false){
		parent::show();
		if(!Core::mustLogin()) return false;
		$page = $page ? $page : Requestlocal::getInt('page',1);
		$mode = Requestlocal::getString('mode','in');
		import('model.user');
		import('model.mail_to_user');
		if($mode=='in'){
			//Входящие
			$settings = array(
				'join' =>array(
					array('table'=>ModelMail_to_user::TABLE, 'key'=>ModelMail_to_user::F_MAIL_ID, 'join_table'=>ModelMail::TABLE, 'join_field'=>ModelMail::F_MAIL_ID),
					array('table'=>ModelUser::TABLE, 'key'=>ModelUser::F_USER_ID, 'join_table'=>ModelMail_to_user::TABLE, 'join_field'=>ModelMail_to_user::F_USER_ID)
				),
				'where' => DB::apostrof(ModelMail_to_user::TABLE.DOT.ModelMail_to_user::F_USER_ID).'='.Core::user(),
				'order' => ModelMail::TABLE.DOT.ModelMail::F_CREATED
			);
			$this->setupPagination($page, $settings);
			$data = $this->model()->load(
				false,
				array(
					ModelUser::TABLE.DOT.ModelUser::F_NAME,
					ModelUser::TABLE.DOT.ModelUser::F_USER_ID,
					ModelMail_to_user::F_MAIL_ID,
					ModelMail_to_user::F_MODE,
					ModelMail::TABLE.DOT.ModelMail::F_TITLE,
					ModelMail::TABLE.DOT.ModelMail::F_DESCRIPTION,
					ModelMail::TABLE.DOT.ModelMail::F_CREATED
				),
				$settings
			);
		}else{
			//Исходяшие
			$settings = array(
				'join' =>array(
					array('table'=>ModelMail_to_user::TABLE, 'key'=>ModelMail_to_user::F_MAIL_ID, 'join_table'=>ModelMail::TABLE, 'join_field'=>ModelMail::F_MAIL_ID),
					array('table'=>ModelUser::TABLE, 'key'=>ModelUser::F_USER_ID, 'join_table'=>ModelMail_to_user::TABLE, 'join_field'=>ModelMail_to_user::F_USER_ID)
				),
				'where' => ModelMail::TABLE.DOT.ModelMail::F_USER_ID.'='.Core::user(),
				'group' => ModelMail::TABLE.DOT.ModelMail::F_MAIL_ID,
				'order' => ModelMail::TABLE.DOT.ModelMail::F_CREATED
			);
			$this->setupPagination($page, $settings);
			$data = $this->model()->load(
				false,
				array(
					ModelUser::TABLE.DOT.ModelUser::F_NAME,
					ModelUser::TABLE.DOT.ModelUser::F_USER_ID,
					ModelMail::F_MAIL_ID,
					ModelMail::F_TITLE,
					ModelMail::F_DESCRIPTION,
					ModelMail::F_CREATED
				),
				$settings
			);
		}
		

		if(Core::isJSON() && Requestlocal::getInt('asTable',null)){
			$this->view->setAll($this->view->tablePack($data));
		} else {
			$this->view->set('list', $data);
			$this->setShowPagination();
		}
        $this->build();
	}
	/**
	 * Просмотр елемента
	 *
	 */
	public function display(){
		parent::display(true);
		import('model.user');
		import('model.mail_to_user');
		$params = array(
			"join" => array(
				array('table'=>ModelMail_to_user::TABLE, 'key'=>ModelMail_to_user::F_MAIL_ID, 'join_table'=>ModelMail::TABLE, 'join_field'=>ModelMail::F_MAIL_ID),
				array('table'=>ModelUser::TABLE, 'key'=>ModelUser::F_USER_ID, 'join_table'=>ModelMail_to_user::TABLE, 'join_field'=>ModelMail_to_user::F_USER_ID)
			)
		);
		$fields = array(
			ModelUser::TABLE.DOT.ModelUser::F_NAME,
			ModelUser::TABLE.DOT.ModelUser::F_USER_ID,
			ModelMail_to_user::F_MAIL_ID,
			ModelMail_to_user::F_MODE,
			ModelMail::TABLE.DOT.ModelMail::F_TITLE,
			ModelMail::TABLE.DOT.ModelMail::F_DESCRIPTION,
			ModelMail::TABLE.DOT.ModelMail::F_CREATED
		);
		$mail = $this->model()->loadOne($this->id,$fields,$params);		
		$this->view->set('element',$mail);
		$this->build();
	}
	public function add(){
		parent::add();
		Core::mustLogin();
		$this->build();
	}
	/**
	 * Создание
	 *
	 */
	public function save(){
		parent::save();
		Core::mustLogin();
		$result=$this->model()->save(
			array(
				ModelMail::F_TITLE=>Requestlocal::getString(ModelMail::F_TITLE),
				ModelMail::F_DESCRIPTION=>Requestlocal::getString(ModelMail::F_DESCRIPTION),
				ModelMail::F_USER_ID=>Core::user(),
				ModelMail::F_CREATED=>Core::date(),
				ModelMail::F_LANG_ID=>Core::lang(),
				ModelMail::F_SYSTEM=>0,
				ModelMail::F_DELETED=>0
			)
		);
		if(!is_array($result)){
		    $result=$this->model('mail_to_user')->save(
    			array(
    				ModelMail_to_user::F_MAIL_ID=>$result,
    				ModelMail_to_user::F_USER_ID=>Requestlocal::getInt(ModelMail::F_USER_ID),
    				ModelMail_to_user::F_MODE=>0
    			)
    		);
		}
		if(is_array($result)){
        	$this->view->result($result);
        } else {
        	$this->view->result(false);
        }
	}
	/**
	 * Удаление
	 *
	 */
	public function delete(){
		Core::mustLogin();
		parent::delete(false);
		$this->findId(true);
		if(!$this->id){
		    $this->show();
		    return;
		}
		//проверяем наше это письмо или прислано нам
		$mail=(int) $this->model()->loadOne($this->id,ModelMail::F_USER_ID);
		if($mail==Core::user()){
		    //пользователи которые получили это письмо
		    if($this->model('mail_to_user')->loadCount(array('where'=>ModelMail_to_user::F_MAIL_ID.'='.$this->id))){
		        $this->model()->save(array(ModelMail::F_DELETED=>1),$this->id);
		    }else{
		        $this->model()->delete($this->id);
		        $this->model()->save(array(ModelMail::F_PARENT_ID=>0),false,array('where'=>ModelMail::F_PARENT_ID."=".$this->id));
		    }
		}else{
		    $this->model('mail_to_user')->delete(false,array('where'=>ModelMail_to_user::F_MAIL_ID.'='.$this->id.' AND '.ModelMail_to_user::F_USER_ID."=".Core::user()));
		    //письмо удалено писавшим и всеми адресатами тогда его удаляем
		    if(!$this->model('mail_to_user')->loadCount(array('where'=>ModelMail_to_user::F_MAIL_ID.'='.$this->id)) && (int) $this->model()->loadOne($this->id,ModelMail::F_DELETED)==1){
		        $this->model()->delete($this->id);
		    }
		}
		coreExit();
		Core::redirect(base64_decode(Vars::_(Core::REFERER)),T::_('Deleted'));
	}
	/**
	* Автокомплит для списка пользователей
	*
	*/
	public function toList(){
		$find = Requestlocal::getString('term');
		$result = array();
		if($find){
			$list = $this->model('user')->load(false,array(ModelUser::F_NAME,ModelUser::F_USER_ID),array(
				"where" => ModelUser::F_NAME." LIKE('%".$find."%')",
				"limit" => 10
			));
			$result = array();
			foreach ($list as $key => $item) {
				$result[] = array(
					"id"    => $item[ModelUser::F_USER_ID],
					"label" => $item[ModelUser::F_NAME],
					"value" => $item[ModelUser::F_NAME]
				);
			}
		}
		$GLOBALS['clean'] = true;
		$this->view->setAll($result);
	}

}